import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Calendar, Clock, Lock, Search, Tag, ArrowRight } from 'lucide-react';
import { loadAllPosts } from '../utils/markdownLoader';
import SEOHead from '../components/SEOHead';

const BlogList = () => {
  const [posts, setPosts] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedTag, setSelectedTag] = useState('');
  const [filteredPosts, setFilteredPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadPosts = async () => {
      try {
        const loadedPosts = await loadAllPosts();
        setPosts(loadedPosts);
        setFilteredPosts(loadedPosts);
      } catch (error) {
        console.error('加载文章失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadPosts();
  }, []);

  useEffect(() => {
    let filtered = posts;

    if (searchTerm) {
      filtered = filtered.filter(post =>
        post.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        post.excerpt.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (selectedTag) {
      filtered = filtered.filter(post => post.tags.includes(selectedTag));
    }

    setFilteredPosts(filtered);
  }, [posts, searchTerm, selectedTag]);

  const allTags = [...new Set(posts.flatMap(post => post.tags))];

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-spring-600 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-300">加载文章中...</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <SEOHead 
        title="技术博客文章"
        description="浏览所有技术博客文章，包括前端开发、后端技术、系统架构等领域的深度技术分享和实践经验。"
        keywords="技术文章,博客列表,前端开发,后端技术,编程教程,技术分享"
      />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      {/* Header */}
      <header className="text-center mb-12">
        <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
          技术博客文章
        </h1>
        <p className="text-lg text-gray-600 dark:text-gray-300 max-w-2xl mx-auto">
          分享技术见解、项目经验和生活感悟
        </p>
      </header>

      {/* Search and Filter */}
      <nav className="mb-8 space-y-4" role="search" aria-label="文章搜索和筛选">
        <div className="relative max-w-md mx-auto">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" />
          <input
            type="text"
            placeholder="搜索文章..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-spring-500 focus:border-transparent"
          />
        </div>

        <div className="flex flex-wrap justify-center gap-2">
          <button
            onClick={() => setSelectedTag('')}
            className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
              selectedTag === ''
                ? 'text-white theme-bg'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
            }`}
          >
            全部
          </button>
          {allTags.map(tag => (
            <button
              key={tag}
              onClick={() => setSelectedTag(tag)}
              className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
                selectedTag === tag
                  ? 'text-white theme-bg'
                  : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
              }`}
            >
              {tag}
            </button>
          ))}
        </div>
      </nav>

      {/* Posts Grid */}
      <main className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8" role="main">
        {filteredPosts.map((post, index) => (
          <article
            key={post.id}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-lg hover:shadow-xl card-animated overflow-hidden animate-fade-in-up opacity-0"
            style={{ 
              animationDelay: `${index * 0.1}s`,
              animationFillMode: 'forwards'
            }}
            itemScope
            itemType="https://schema.org/BlogPosting"
          >
            {post.image && (
              <div className="h-48 bg-gray-200 dark:bg-gray-700 overflow-hidden group">
                <img
                  src={post.image}
                  alt={`${post.title}的配图`}
                  className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                  itemProp="image"
                  loading="lazy"
                />
              </div>
            )}
            
            <div className="p-6">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center text-sm text-gray-500 dark:text-gray-400">
                  <Calendar className="h-4 w-4 mr-1" />
                  {formatDate(post.date)}
                </div>
                {post.encrypted && (
                  <Lock className="h-4 w-4 text-yellow-500" />
                )}
              </div>

              <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-3 line-clamp-2" itemProp="headline">
                {post.title}
              </h2>
              
              <meta itemProp="datePublished" content={post.date} />
              <meta itemProp="author" content="技术博主" />

              <p className="text-gray-600 dark:text-gray-300 mb-4 line-clamp-3" itemProp="description">
                {post.excerpt}
              </p>

              <div className="flex items-center justify-between">
              <div className="flex flex-wrap gap-1">
                {post.tags.slice(0, 2).map(tag => (
                  <span
                    key={tag}
                    className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium"
                    style={{
                      backgroundColor: 'var(--color-primary-light)',
                      color: 'var(--color-primary-dark)'
                    }}
                  >
                    <Tag className="h-3 w-3 mr-1" />
                    {tag}
                  </span>
                ))}
                  {post.tags.length > 2 && (
                    <span className="text-xs text-gray-500 dark:text-gray-400">
                      +{post.tags.length - 2}
                    </span>
                  )}
                </div>

                <div className="flex items-center text-sm text-gray-500 dark:text-gray-400">
                  <Clock className="h-4 w-4 mr-1" />
                  {post.readTime}
                </div>
              </div>

              <Link
                to={`/blog/${post.id}`}
                className="inline-flex items-center mt-4 font-medium transition-all duration-300 theme-color hover:opacity-80 group"
                aria-label={`阅读文章：${post.title}`}
                itemProp="url"
              >
                阅读全文
                <ArrowRight className="ml-1 h-4 w-4 group-hover:translate-x-1 transition-transform" />
              </Link>
            </div>
          </article>
        ))}
      </main>

      {filteredPosts.length === 0 && (
        <div className="text-center py-12">
          <p className="text-gray-500 dark:text-gray-400 text-lg">
            没有找到匹配的文章
          </p>
        </div>
      )}
      </div>
    </>
  );
};

export default BlogList;
